<template>
  <div>


    <div class="flex justify-between">
      <div class="flex-1 overflow-x-auto flex">
        <div class="mt-2 ml-2 text-left border px-2 py-1 select-none ">
          <span v-for="tag in TagList" :key="tag.id" @click="selectTag(tag.id)">
            <q-chip
                    class="  cursor-pointer p-2 mr-2 rounded-md  hover:bg-blue-400"
                    :class="CurrTag == tag.id ? 'bg-orange-300' :'bg-gray-200'"
            >
            {{ tag.Name }}
          </q-chip>
          </span>

        </div>
      </div>

      <div class="mx-1 mt-2.5  p-1 w-48">
        <input type="text" v-model="SearchText"
               class="w-full border  px-4 py-2.5 text-gray-700 bg-white rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
               placeholder="输入关键词按回车搜索" @keydown.enter="SearchList">
<!--        <div class="mt-1 flex justify-end">-->
<!--          <q-btn  class="rounded-xl  bg-blue-4">搜索</q-btn>-->
<!--        </div>-->
      </div>
    </div>

    <div class="mt-4  flex  ">
      <div v-for="app in AppList" :key="app.id"
           class="px-2 w-1/3   mb-4  rounded-md ">

        <div class="px-2 border">
          <!-- 按钮-->
          <div class="flex justify-between mt-2  pb-1 select-none">
            <div class="text-blue-600">
              <b class="hover:cursor-pointer">
                {{app.tool_name}}
                <q-tooltip>应用发布时间: {{ParseGoDateStr(app.created_at)}} <br>发布者：{{app.share_user_name}}</q-tooltip>
              </b>
              <q-chip color="orange" class="hover:cursor-pointer ml-0.5 rounded-sm" :style="{ borderRadius: '40%' }"  dense outline >
                {{FormatNum(app.use_nums)}}
                <q-tooltip>应用被添加使用次数</q-tooltip>
              </q-chip>
            </div>
            <div class="">
<!--              <button class="mr-2 bg-orange-400 text-white px-1 py-0.5 rounded-md" @click="">使用</button>-->
              <button class="bg-cyan-500 text-white px-1 py-0.5 rounded-md" @click="UseApp(app)">
                 添加
                <q-tooltip>添加到我的应用列表中</q-tooltip>
              </button>
            </div>

          </div>

          <!-- 主题 prompt内容-->
          <div class="text-left my-1 "  style="height: 180px;overflow-y: auto">{{ app.prompt }}</div>

          <!-- 底部 模板的标签-->
          <div class="flex justify-between border-t ">
              <div>
               <span v-for="tagId in app.tag_ids.split(',').map(s=>parseInt(s))"
                     :key="tagId" @click="selectTag(tagId)"  >
                  <q-chip  v-if="tagId > 1"  dense class="bg-green-2  hover:bg-blue-200  cursor-pointer p-1 px-2 mr-1 rounded-md">
                     {{ MapTag[tagId]}}
                  </q-chip>
               </span>
              </div>
              <div class="pt-0.5">
                  @<b>{{app.share_user_name}}</b>
              </div>
          </div>
        </div>

      </div>
    </div>

  </div>

  <div class="text-center my-2 mr-2">
    <q-btn outline class="ml-1"  color="gray" :label="CurrAppPage+'/'+TotalPageApp" />
    <q-btn :disable="CurrAppPage==1" outline class="ml-1" color="primary" label="上一页" @click="LastPage()" />
    <q-btn :disable="CurrAppPage==TotalPageApp" outline class="ml-1" color="primary" label="下一页" @click="NextPage()" />
  </div>

</template>

<script setup lang="ts">
import {onMounted, ref} from 'vue';
import {ApiAppAddUseNum, ApiAppGetList, ApiAppTagGetList} from "../../wailsjs/go/service/BackService";
import {comdto, dbdto, service} from "../../wailsjs/go/models";
import {FormatNum} from "../utils/num";
import {useIndexStore} from "../store";
import {CreateUserTool} from "../../wailsjs/go/dbservice/UserToolService";
import {ToastError, ToastInfo} from "../utils/Toast";
import {RespCodeOk} from "../constant/enums/RespCode";
import {ParseGoDateStr} from "../utils/dates";
import {Loading} from "quasar";

let SearchText=ref("")
let CurrTag=ref(1)

const isBottom = ref(false)

onMounted(() => {
  GetTagList()
  GetAppList()
  document.addEventListener('scroll', handleScroll)
})


let storeIndex=ref(useIndexStore())
function UseApp(app:any){
  let appData =app as dbdto.UserToolAdd
  CreateUserTool(appData).then((res: any) => {
    if(res.code == RespCodeOk){
      ToastInfo("已经将应用添加到我的应用列表中")

      //将应用使用次数+1
      let update =new comdto.RequestAppUpdate()
      update.app_id=app["id"]
      ApiAppAddUseNum(update)
    }else{
      ToastError(res.msg)
    }

  })
}

let TagList=ref<Array<comdto.AppTagInfo>>([])
let MapTag=ref<Record<number, string>>({})
function GetTagList() {
  let requestParam =new comdto.FindExtra
  requestParam.limit=10
  requestParam.offset=0
  requestParam.order_by_column="id"
  requestParam.order_by_desc=false
  ApiAppTagGetList(requestParam).then((res:service.HttpResp)=>{
     console.log(res,"ApiAppTagGetList ---res")
     TagList.value=res.data as  any as Array<comdto.AppTagInfo>
     for (let i = 0; i < TagList.value.length; i++) {
         let item=TagList.value[i]
         MapTag.value[item.id]=item.Name
     }
  })
}


let AppList=ref<Array<comdto.AppInfo>>([])
let CurrAppPage=ref(1)
let CurrAppPageSize=ref(6)
let TotalPageApp=ref(0)

function GetAppList() {
  Loading.show()
  let requestParam =new comdto.FindExtra
  requestParam.limit=CurrAppPageSize.value

  requestParam.offset= (CurrAppPage.value - 1) * CurrAppPage.value
  requestParam.order_by_column="use_nums"
  requestParam.order_by_desc=true
  let tagIdStr =CurrTag.value == 1 ? "" : String(CurrTag.value)+","

  ApiAppGetList(requestParam,SearchText.value,tagIdStr).then((res: service.HttpResp)=>{
    Loading.hide()
    console.log(res,"ApiAppGetList ---res")
    AppList.value = res.data as any as Array<comdto.AppInfo>
    let total=res.extra as any as Array<number>[0]
    TotalPageApp.value = total == 0 ? 0 : Math.ceil(total/CurrAppPageSize.value )
    CurrAppPage.value =CurrAppPage.value == 0 ? 1 : CurrAppPage.value
    CurrAppPage.value= TotalPageApp.value ==0 ? 0 : CurrAppPage.value

  })

  //计算5个数的和
}
function NextPage(){
  CurrAppPage.value +=1
  GetAppList()
}
function LastPage(){
  CurrAppPage.value -=1
  GetAppList()
}



function handleScroll() {
  const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
  const windowHeight = document.documentElement.clientHeight || document.body.clientHeight
  const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight
  if (scrollTop + windowHeight >= scrollHeight - 10) { // 判断是否到达底部，这里使用了10的误差值
    isBottom.value = true
  } else {
    isBottom.value = false
  }
}


const selectTag = (tagId: number) => {
  CurrAppPage.value=1
  CurrTag.value=tagId
  GetAppList()
  console.log(CurrTag.value," ---CurrTag.value")
 // selectedTag.value = tag;
};

function SearchList(){
  CurrAppPage.value=1
  GetAppList()
}





</script>

<style scoped>
/* tailwindcss 样式 */
</style>